import sys
import subprocess

##################################################################
#  ______   __     __         __         ______     __     __    #
# /\  == \ /\ \   /\ \       /\ \       /\  __ \   /\ \  _ \ \   #
# \ \  _-/ \ \ \  \ \ \____  \ \ \____  \ \ \/\ \  \ \ \/ ".\ \  #
#  \ \_\    \ \_\  \ \_____\  \ \_____\  \ \_____\  \ \__/".~\_\ #
#   \/_/     \/_/   \/_____/   \/_____/   \/_____/   \/_/   \/_/ #
#                                                                #
##################################################################

# Obtener la ruta del ejecutable de Python en Blender
PYTHON = sys.executable
PILLOW = "Pillow"


def pillow_is_installed() -> bool:
    #################################################################
    # Check if pillow are previously installed, with pip show pillow:
    #################################################################
    try:
        subprocess.check_call([PYTHON, "-m", "pip", "show", PILLOW], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return True
    except subprocess.CalledProcessError:
        return False


def install_pillow() -> bool:
    
    PIL_INSTALLED = pillow_is_installed()
    if PIL_INSTALLED:
        print("\n⏺ Pillow was already previously installed, nothing extra will be done. \n ")
        return True

    try:        
        # Actualizar pip
        print("\n⏺ Update pip...")
        update_pip_command = [PYTHON, "-m", "pip", "install", "--upgrade", "pip"]
        subprocess.check_call(update_pip_command)
        
        print("\n⏺ Installing Pillow...")
        # Comando para instalar el paquete utilizando el ejecutable de Python de Blender
        install_command = [PYTHON, "-m", "pip", "install", PILLOW]
        subprocess.check_call(install_command)
        return True

    except subprocess.CalledProcessError as e:
        print(f"\n⏺ Error installing Pillow: {e}")
        print(f"⏺ Pillow may not have been installed correctly. \n ")
        return False


def uninstall_pillow() -> None:

    PIL_INSTALLED = pillow_is_installed()
    if PIL_INSTALLED:
        print("\n ⏺ Uninstalling pillow.")
        uninstall_command = [PYTHON, "-m", "pip", "uninstall", "-y", PILLOW]
        subprocess.check_call(uninstall_command)